package com.appprogram.baseapppackage;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;

import com.appprogram.baseapppackage.constant.Constants;
import com.appprogram.baseapppackage.databinding.MainActivityBinding;
import com.appprogram.baseapppackage.notchtools.NotchTools;
import com.appprogram.baseapppackage.util.AppUpdateUtil;
import com.appprogram.baseapppackage.util.ImageUpLoad;
import com.appprogram.baseapppackage.util.PictureSelectorConfig;
import com.appprogram.baseapppackage.widget.MyWebViewClient;
import com.blankj.utilcode.util.LogUtils;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebChromeClient;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.noober.background.BackgroundLibrary;
import com.wang.avi.indicators.BallSpinFadeLoaderIndicator;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;

public class MainActivity extends AppCompatActivity {
    protected long exitTime = 0L;
    private AppCompatActivity mContext;
    private List<LocalMedia> mLocalMedia = new ArrayList<>();
    private MainActivityBinding mBinding;
    private AgentWeb agentWeb;
    /*动态获取的上传图片地址*/
    private String httpUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //适配全面屏、刘海屏
        NotchTools.getFullScreenTools().fullScreenUseStatus(this);
        BackgroundLibrary.inject(this);
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.main_activity);
        mContext = this;
        initLoading();
        initWebView();
    }

    //初始化WebView
    private void initWebView() {
        agentWeb = AgentWeb.with(this)
                .setAgentWebParent(mBinding.container, new FrameLayout.LayoutParams(-1, -1))
                .closeIndicator()
                .setWebViewClient(new MyWebViewClient())
                .setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onProgressChanged(WebView view, int newProgress) {
                        super.onProgressChanged(view, newProgress);
                        if (newProgress == 100) mBinding.rlLoading.setVisibility(View.GONE);
                        else mBinding.rlLoading.setVisibility(View.VISIBLE);
                    }
                })
                .createAgentWeb().ready()
                .go(Constants.BASE_URL);
        //agentWeb.getAgentWebSettings().getWebSettings().setJavaScriptEnabled(false);
        agentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface());
    }

    //初始化loading
    private void initLoading() {
        //mBinding.simpleBackground.setImageResource(R.drawable.bg_loading);
        mBinding.aviLoading.setIndicator(new BallSpinFadeLoaderIndicator());
        mBinding.aviLoading.setIndicatorColor(ContextCompat.getColor(this, R.color.colorAccent));
    }

    @Override
    public void onBackPressed() {
        if (null != agentWeb && !agentWeb.back()) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toasty.info(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
        }
    }

    @Override
    protected void onPause() {
        if (null != agentWeb) agentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (null != agentWeb) agentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (null != agentWeb) agentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (agentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                LogUtils.e("选择图片/拍照完成");
                //相册选择结果
                mLocalMedia = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回五种path
                // 1.media.getPath(); 原图path
                // 2.media.getCutPath();裁剪后path，需判断media.isCut();切勿直接使用
                // 3.media.getCompressPath();压缩后path，需判断media.isCompressed();切勿直接使用
                // 4.media.getOriginalPath()); media.isOriginal());为true时此字段才有值
                // 5.media.getAndroidQToPath();Android Q版本特有返回的字段，但如果开启了压缩或裁剪还是取裁剪或压缩路
                // 径；注意：.isAndroidQTransform(false);此字段将返回空
                // 如果同时开启裁剪和压缩，则取压缩路径为准因为是先裁剪后压缩
                if (mLocalMedia.size() > 0) {
                    ImageUpLoad.getInstance().uploadImage(mLocalMedia.get(0).getCompressPath(), (resultData, resultInfo) -> {
                        //mAgentWeb.getJsAccessEntrace().quickCallJs("callByAndroid");
                    }, 0);
                }
            }
        }
    }

    public class AndroidInterface {
        @JavascriptInterface
        public int getType() {
            return 1;
        }

        @JavascriptInterface
        public String upType() {
            return httpUrl;
        }

        @JavascriptInterface
        public void upImage() {
            // 这种弹窗从 1.0.0版本开始实现了优雅的手势交互和智能嵌套滚动
            new XPopup.Builder(mContext)
                    .asBottomList("请选择一项", new String[]{"相机", "相册"}, (position, text) -> {
                        if (position == 0) {//相机
                            PictureSelectorConfig.getInstance().openCamera(mContext);
                        } else if (position == 1) {//相册
                            PictureSelectorConfig.getInstance().create(mContext, mLocalMedia);
                        }
                    })
                    .show();
        }

        @JavascriptInterface
        public void appHasNewVersion(String appUrl, String title, String content) {
            //App升级
            // appUrl https://down.lytuolian.com/soft/yixiaoduo/yixiaoduo.v1.3.apk
            // title 新版本升级
            // content 修改了若干bug
            AppUpdateUtil.getInstance().update(mContext, appUrl, title, content);
        }
    }
}
